package com.arthas.arthasforsba.app.web;


import com.arthas.arthasforsba.constant.Constants;
import com.arthas.arthasforsba.utils.BashUtil;
import com.arthas.arthasforsba.utils.file.FileUploadUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ResourceLoader;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.*;


/**
 * @author dingling
 * @desc 文件管理
 * @date 2023-07-19 16:01
 **/
@RequestMapping("/api/files")
@RestController
public class FileController {

    @Autowired
    ResourceLoader resourceLoader;

    @Value(value = "${file.base:/data/work/files/}")
    private String filePath;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Map<String,Object> uploadFile(String targetIp, MultipartFile file) throws IOException {
        //获取文件名
        String fileName = file.getOriginalFilename();
        Assert.notNull(fileName,"文件名不可为空！");
        Assert.notNull(targetIp,"目标id不能为空！");
        //获取文件后缀名
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        //重新生成文件名
        fileName = UUID.randomUUID()+suffixName;
        // todo 先存到 /data/file/targetIp/ 下 ，
        //  后通过执行bat命令 转移到目标路径 /data/file/targetIp/
        //  不输入密码传输 需要先生成密匙和公匙
//        List<String> param = Arrays.asList(filePath,targetIp,fileName);
        List<String> param = Arrays.asList("/mydata/files/arthas-file",targetIp,fileName);
        FileUploadUtils.upload(filePath+"/"+targetIp,file);
        InputStream inputStream = resourceLoader.getResource(Constants.SCP_BAT_PATH).getInputStream();
        Map<String, String> execMsg = BashUtil.runExecution2(inputStream, param);
        HashMap<String, Object> map = new HashMap<>();
        if (execMsg.get("msg") != null){
            map.put("msg",execMsg.get("msg"));
            map.put("status","error");
        }else{
            map.put("status","ok");
        }
        System.out.println(map);
        return map;
    }

}
